﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using WebAPISample.Cors;

namespace WebAPISample.Controllers
{
    public class UserController : ApiController
    {
        /// <summary>
        /// 验证用户合法性
        /// </summary>
        /// <returns>验证成功返回Token</returns>
        [HttpGet]
        [Route("Login")]
        public HttpResponseMessage Login()
        {
            var resultEntity = ResultEntity.CreateResultEntity<string>();
            try
            {
                bool Validate = ValidateUser();
                if (Validate)
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(0, "admin", DateTime.Now,
                              DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", "admin", "123456"),
                              FormsAuthentication.FormsCookiePath);
                    //返回登录结果、用户信息、用户验证票据信息

                    resultEntity.IsSucess = true;
                    resultEntity.Data = FormsAuthentication.Encrypt(ticket);
                }
                else
                {
                    resultEntity.IsSucess = false;
                    resultEntity.Data = string.Empty;
                }
            }
            catch (Exception ex)
            {
                resultEntity.IsSucess = false;
                resultEntity.Message = ex.Message;
            }

            //将身份信息保存在session中，验证当前请求是否是有效请求
            var strJson = Newtonsoft.Json.JsonConvert.SerializeObject(resultEntity);
            var resp = new HttpResponseMessage { Content = new StringContent(strJson, System.Text.Encoding.UTF8, "application/json") };

            return resp;
        }

        private bool ValidateUser()
        {
            return true;
        }
    }
}